package com.summer.tools.common.utils;

/**
 * @author john
 */
public class HexUtil {

    private HexUtil() {}

    private static final String HEX_STR = "0123456789abcdef";

    public static String toString(byte[] btArr) {

        StringBuilder stringBuilder = new StringBuilder();
        if (btArr == null || btArr.length <= 0) {
            return null;
        }
        for (byte b : btArr) {
            int v = b & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * @param hexStr 字符串
     * @return 字节数组
     */
    public static byte[] toByteArr(String hexStr) {

        if (hexStr == null) {
            return new byte[0];
        }

        char[] charArr = hexStr.toCharArray();
        byte[] btArr = new byte[charArr.length / 2];
        int index = 0;
        for (int i = 0; i < charArr.length; i++) {
            int highBit = HEX_STR.indexOf(charArr[i]);
            int lowBit = HEX_STR.indexOf(charArr[++i]);
            btArr[index] = (byte) (highBit << 4 | lowBit);
            index++;
        }
        return btArr;
    }
}
